//
//  CCWebViewController.m
//  BuDeJie
//
//  Created by demoncraz on 2017/2/12.
//  Copyright © 2017年 demoncraz. All rights reserved.
//

#import "CCWebViewController.h"
#import <WebKit/WebKit.h>

@interface CCWebViewController ()
@property (weak, nonatomic) IBOutlet UIBarButtonItem *backItem;
@property (weak, nonatomic) IBOutlet UIBarButtonItem *forwardItem;
@property (weak, nonatomic) IBOutlet UIView *contentView;
@property (weak, nonatomic) IBOutlet UIProgressView *progressView;

@property (nonatomic, weak) WKWebView *webView;

@end

@implementation CCWebViewController

- (IBAction)goBackClick:(id)sender {
    [self.webView goBack];
}
- (IBAction)goForwardClick:(id)sender {
    [self.webView goForward];
}
- (IBAction)reloadClick:(id)sender {
    [self.webView reload];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    //创建一个MKWebView
    WKWebView *webView = [[WKWebView alloc] init];
    _webView = webView;
    NSURLRequest *request = [NSURLRequest requestWithURL:_url];
    [self.contentView addSubview:webView];
    [webView loadRequest:request];
    
    [webView addObserver:self forKeyPath:@"canGoBack" options:NSKeyValueObservingOptionNew context:nil];
    [webView addObserver:self forKeyPath:@"canGoForward" options:NSKeyValueObservingOptionNew context:nil];
    [webView addObserver:self forKeyPath:@"title" options:NSKeyValueObservingOptionNew context:nil];
    [webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
}

#pragma KVO函数
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
    self.backItem.enabled = self.webView.canGoBack;
    self.forwardItem.enabled = self.webView.canGoForward;
    self.title = self.webView.title;
    self.progressView.progress = self.webView.estimatedProgress;
    self.progressView.hidden = self.webView.estimatedProgress >= 1;
}


- (void)dealloc {
    [self.webView removeObserver:self forKeyPath:@"canGoBack" context:nil];
    [self.webView removeObserver:self forKeyPath:@"canGoForward" context:nil];
    [self.webView removeObserver:self forKeyPath:@"title" context:nil];
    [self.webView removeObserver:self forKeyPath:@"estimatedProgress" context:nil];
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    self.webView.frame = self.view.bounds;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
